package com.zxc.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zxc.common.to.mq.SeckillOrderTo;
import com.zxc.common.utils.R;
import com.zxc.common.vo.MemberRespVo;
import com.zxc.gulimall.seckill.feign.CouponFeignService;
import com.zxc.gulimall.seckill.feign.ProductFeignService;
import com.zxc.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.zxc.gulimall.seckill.service.SeckillService;
import com.zxc.gulimall.seckill.to.SeckillSkuRedisTo;
import com.zxc.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.zxc.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    private final String SESSION__CACHE_PREFIX = "seckill:sessions:";

    private final String SECKILL_CHARE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSkuLatest3Days() {

        //1、扫描最近三天的商品需要参加秒杀的活动
        R lates3DaySession = couponFeignService.getLate3DaySession();
        if (lates3DaySession.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkusVo> sessionData = lates3DaySession.getData("data", new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }

    }

    /*
    *
    * 获取当前可以参加秒杀的商品信息
    * */
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀场次。
        long time = new Date().getTime(); //1970 == 》 now
        Set<String> keys = redisTemplate.keys(SESSION__CACHE_PREFIX + "*");//获取当前秒杀的商品的信息对应的key值
        for (String key : keys) {
            //获取秒杀时间的时间字符串区间
            String replace = key.replace(SESSION__CACHE_PREFIX,"");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);

            //说明在时间区间
            if (time >= start && time <= end){
                //2、获取这个秒杀场次的商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);//获取所有的商品秒杀的信息
                BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                List<String> multiGet = boundHashOps.multiGet(range);
                //具体信息
                if (multiGet != null){
                    List<SeckillSkuRedisTo> collect = multiGet.stream().map(item -> {
                        //预告秒杀不能返回随机码randomCode，开始秒杀需要返回随机码
                        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());

                    //当前所有可以参与秒杀的商品
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0){
            String regx = "\\d-" + skuId;
            for (String key : keys){
                if (Pattern.matches(regx,key)){
                    //如果匹配上，说明该商品需要参加秒杀活动
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    //当前不是秒杀时间的话，我们不能携带秒杀随机码
                    Long nowTime = new Date().getTime();
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    if (nowTime >= startTime && nowTime <= endTime){

                    }else {
                        skuRedisTo.setRandomCode(null);
                    }

                    return skuRedisTo;
                }
            }
        }

        return null;
    }


    //秒杀商品请求 TODO 秒杀商品的时候，每一个数据都有它的过期的时间
    // TODO ，秒杀后续的流程简化了收货地址
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String,String> hashOperations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        //2、获取秒杀单的信息
        String json = hashOperations.get(killId);
        if (StringUtils.isEmpty(json)){
            return null;
        }else {
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //1、校验合法性（秒杀时间是否已过)
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            Long nowTime = new Date().getTime();

            Long ttl = endTime - nowTime;//redisKey的过期时间，防止一个人多次购买

            if (nowTime <= endTime && nowTime >= startTime){
                //2、校验随机码和商品id
                String randomCode = skuRedisTo.getRandomCode();
                String skuId = skuRedisTo.getPromotionSessionId()+"-"+skuRedisTo.getSkuId();//键key
                if (randomCode.equals(key) && killId.equals(skuId)){
                    //3、验证购物数量是否合理
                    if (num <= skuRedisTo.getSeckillLimit()){
                        //4、是否验证这个人是否买过这个产品（幂等性）；如果秒杀成功就去占位
                        String redisKey = memberRespVo.getId()+"_"+skuId;//USER_ID_秒杀活动ID_商品ID，防止重复秒杀
                        //设置自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);//SETNX
                        if (aBoolean){
                            //占位成功说明此用户没有购买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                                //boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                boolean b = semaphore.tryAcquire(num);
                                if (b){
                                    //拿到信号量，秒杀成功
                                    //快速下单，发送MQ消息
                                    String orderSn = IdWorker.getTimeId();//创建订单号

                                    //给rabbitmq发送消息，秒杀下单成功
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderSn(orderSn);
                                    seckillOrderTo.setNum(num);
                                    seckillOrderTo.setMemberId(memberRespVo.getId());
                                    seckillOrderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                    seckillOrderTo.setSkuId(skuRedisTo.getSkuId());
                                    seckillOrderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());

                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                    log.info("秒杀成功，发送消息给秒杀订单队列......");
                                    long s2 = System.currentTimeMillis();
                                    log.info("耗时..." + (s2 - s1));
                                    return orderSn;
                                }else {
                                    return null;
                                }

                        }else {
                            return null;
                        }
                    }
                }

            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 缓存秒杀活动信息
     * @param sessions
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessions) {

        sessions.stream().forEach(session -> {

            //获取当前活动的开始和结束时间的时间戳
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();

            //存入到Redis中的key
            String key = SESSION__CACHE_PREFIX + startTime + "_" + endTime;

            //判断Redis中是否有该信息，如果没有才进行添加，保证幂等性，不重复添加活动信息
            Boolean hasKey = redisTemplate.hasKey(key);

            //缓存活动信息
            if (!hasKey) {
                //获取到活动中所有商品的skuId
                List<String> skuIds = session.getRelationSkus().stream() // value ==> 活动信息PromotionSessionId + 商品Id
                        .map(item -> item.getPromotionSessionId() + "-" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,skuIds);
            }
        });

    }

    /**
     * 缓存秒杀活动所关联的商品信息
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> sessions) {

        sessions.stream().forEach(session -> {
            //准备hash操作，绑定hash
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //生成随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                //使用秒杀活动场次Id+秒杀商品Id作为key 表示缓存秒杀活动锁关联的商品信息
                String redisKey = seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString();

                //如果没有上架的商品信息，那么我们保存秒杀商品信息
                if (!operations.hasKey(redisKey)) {

                    //缓存我们商品信息
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    Long skuId = seckillSkuVo.getSkuId();
                    //1、先查询sku的基本信息，调用远程服务
                    R info = productFeignService.getSkuInfo(skuId);
                    if (info.getCode() == 0) {
                        SkuInfoVo skuInfo = info.getData("skuInfo",new TypeReference<SkuInfoVo>(){});
                        redisTo.setSkuInfo(skuInfo);
                    }

                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);

                    //3、设置当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4、设置商品的随机码（防止恶意攻击）
                    redisTo.setRandomCode(token);

                    //序列化json格式存入Redis中
                    String seckillValue = JSON.toJSONString(redisTo);
                    operations.put(seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString(),seckillValue);

                    //如果当前这个场次的商品库存信息已经上架就不需要上架
                    //5、使用库存作为分布式Redisson信号量（限流）
                    // 使用库存作为分布式信号量   （库存信息）
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }

}
